//初始化树结构（合并初始化）== 组织管理
var NodeSettingManagement;
NodeSettingManagement = $.extend({}, setting1, setting2);
var orgTree_ = new VanyBaseTree("treeDemo", baseUrl + "/base/org/queryOrgTree?token=" + sessionStorage.token, NodeSettingManagement);

setTimeout(function thisTree(){
	Jurisdiction();
	//判断是否展示操作区域按钮
	JurisdictionBefore("#treeTitle", "#rMenu");
	try {
		//alert($.fn.zTree.getZTreeObj("treeDemo"));
		//var seletedOrgNode = $.fn.zTree.getZTreeObj("treeDemo").getSelectedNodes()[0];
		table_.orgCode = '000000';
		table_pageIndex=1;
		//table_.orgName = '';
		table_.getData();
	} catch(e) {
		console.log(e)
	}
},100);
//树子节点排序功能
var treeSortOrg = sortOrg("sortOrgPersons", baseUrl + "/base/org/queryOrgUserForSort");

//标题中新增
var titleNode;
new Vue({
	el: "#treeTitle",
	methods: {
		titleOperation: function() {
			$("#titleOperation").css("visibility", "visible");
		},
		addTitle: function() {
			$("#titleOperation").css("visibility", "hidden");
			addNodes.resetForm("ruleForm");
			addNodes.showVisible = true;
			addNodes.treeAddVisible = true;
			//判断是否新增根节点
			titleNode = true;
		},
		ImportOrganization: function() {
			//导入组织
			$(".errorMessage").remove();
			ImportOrg.OrgImportVisible = true;
		}
	}
});

//鼠标点击其他区域，弹框隐藏
$("body").bind("mousedown", function(event) {
	if(!(event.target.id == "titleOperation" || $(event.target).parents("#titleOperation").length > 0)) {
		$("#titleOperation").css("visibility", "hidden");
	}
});

// 树节点操作
new Vue({
	el: '#rMenu',
	methods: {
		// 删除节点
		del: function() {
			hideRMenu();
			tanchuDialog(); //弹出框位置
			var self = this;
			self.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				hideRMenu();
				VanyAjax("/base/org/delete", {
					orgCode: zTree.getSelectedNodes()[0].id
				}).done(function(data) {
					removeTreeNode(zTree.getSelectedNodes()[0]);
					VanyAjax.prototype.hideLoading();
					self.$message({
						type: 'success',
						message: '删除成功!'
					});
				}, true, this);
			}).catch(function() {
				self.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 升级为根节点
		addroot: function() {
			hideRMenu();
			tanchuDialog(); //弹出框位置
			this.$confirm('确认升级为根节点?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: "notLoadingThis"
			}).then(function() {
				VanyAjax("/base/org/updateToRoot", {
					orgCode: zTree.getSelectedNodes()[0].id,
				}).done(function(data) {
					VanyBaseTree("treeDemo", baseUrl + "/base/org/queryOrgTree?token=" + sessionStorage.token, NodeSettingManagement);
				}, false, this);
			}).catch(function() {})
		},
		// 新增节点
		add: function() {
			hideRMenu();
			tanchuDialog(); //弹出框位置
			var treeKey = zTree.getSelectedNodes()[0];
			titleNode = false;
			addNodes.showVisible = false;
			addNodes.resetForm("ruleForm");
			addNodes.treeAddVisible = true;
			addNodes.ruleForm.parentName = treeKey.id;
			addNodes.parentName.push({
				name: treeKey.name,
				id: treeKey.id
			});
		},
		// 编辑节点
		Edit: function() {
			hideRMenu();
			tanchuDialog(); //弹出框位置
			treeEdit.resetForm("ruleForm");
			// 获取树节点相关信息
			var treeKey = zTree.getSelectedNodes()[0];
			for(var key in treeKey) {
				treeEdit.ruleForm[key] = treeKey[key];
			}
			treeEdit.ruleForm.parentName = treeKey.id;
			treeEdit.treeEditVisible = true;
			treeEdit.parentName.push({
				name: treeKey.parentName,
				id: treeKey.pId
			});
			if(treeEdit.parentName[0].id == null) {
				treeEdit.showParent = false;
			} else {
				treeEdit.showParent = true;
			}
		},
		//导出组织
		ExportOrganization: function() {
			hideRMenu();
			tanchuDialog(); //弹出框位置
			var self = this;
			self.$confirm('确认导出?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: "notLoadingThis"
			}).then(function() {
				location.href = "/base/org/export?token=" + sessionStorage.token + "&orgCode=" + zTree.getSelectedNodes()[0].id;
			}).catch(function() {})
		},
		// 人员排序
		PaixuTreeNode: function() {
			hideRMenu();
			tanchuDialog(); //弹出框位置
			treeSortOrg.params.orgCode = table_.orgCode;
			treeSortOrg.getOrgPersons();
		}
	}
});

//新增节点
var addNodes = new Vue({
	el: "#addRole",
	data: function() {
		this.ParentOrgFilter = null;
		//自定义验证，验证机构编码
		var checkId = function(rule, value, callback) {
			if(!value) {
				return callback(new Error('请输入机构编码'));
			}
			setTimeout(function() {
				//中文判断
				if(!/^[a-zA-Z0-9_]{0,}$/.test(addNodes.ruleForm.id)) {
					callback(new Error('编码不能为中文字符'));
				} else {
					callback();
				}
			});
		};
		return {
			showVisible: false,
			treeAddVisible: false,
			labelPosition: 'right',
			ruleForm: {
				parentName: '',
				id: '',
				name: '',
				officeTel: ''
			},
			parentName: [],
			rules: {
				id: {
					required: true,
					validator: checkId,
					trigger: 'blur'
				},
				name: {
					required: true,
					message: '请输入机构名称',
					trigger: 'blur'
				}
			}
		};
	},
	methods: {
		submitForm: function(formName) {
			var self = this;
			self.$refs[formName].validate(function(valid) {
				var parentOrgCodeNodeId;
				if(valid) {
					//判断是否有父级节点
					if(titleNode) {
						parentOrgCodeNodeId = '';
					} else {
						parentOrgCodeNodeId = addNodes.parentName[0].id;
					}
					addNodes.treeAddVisible = false;
					VanyAjax("/base/org/add", {
						orgCode: addNodes.ruleForm.id,
						parentOrgCode: parentOrgCodeNodeId,
						orgName: addNodes.ruleForm.name,
						officeTel: addNodes.ruleForm.officeTel
					}).done(function(data) {
						var newNode = {
							id: addNodes.ruleForm.id,
							name: addNodes.ruleForm.name,
							officeTel: addNodes.ruleForm.officeTel
						};
						if(titleNode) {
							//判断是否是标题中的新增节点，如果是，则新增根节点
							zTree.addNodes(null, newNode);
						} else {
							//不是，则新增当前节点的子节点
							zTree.addNodes(zTree.getNodeByParam("id", parentOrgCodeNodeId, null), -1, newNode, false);
						}
						VanyAjax.prototype.hideLoading();
						self.resetForm("ruleForm");
					}, true, this);
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		openParentOrg: function() {
			var self = this;
			treeEdit.showParent = true;
			if(!this.ParentOrgFilter) {
				this.ParentOrgFilter = VanyFilter({
					mountEl: "#content",
					title: "更换父机构",
					tabs: [{
						"name": "父机构选择",
						"id": "bumen",
						"url": baseUrl + "/base/org/queryOrgTreeWithOutSelf?orgCode=" + zTree.getSelectedNodes()[0].id,
						"writeBackIds": this.ruleForm.parentName,
						"singleSelet": true,
						"defaultProps": {
							children: 'children',
							label: 'name',
							id: "id"
						},
						"icon": '/templates/img/zuzhi.png'
					}],
					ok: function() {
						treeEdit.showParent = true;
						self.parentName = this.tabs[0].allCheckeds;
						self.ruleForm.parentName = this.tabs[0].allNodesId.join(",");
						this.hide();
					}
				});
			} else {
				this.ParentOrgFilter.show();
			}
		},
		resetForm: function(formName) {
			try {
				this.$refs[formName].resetFields();
			} catch(e) {

			}
			this.parentName = [];
			this.ruleForm.parentName = '';
			this.ruleForm.id = '';
			this.ruleForm.name = '';
			this.ruleForm.officeTel = '';
		} //重置
	}
});

//前端删除节点
function removeTreeNode(self) {
	var nodes = zTree.getSelectedNodes();
	if(nodes && nodes.length > 0) {
		zTree.removeNode(nodes[0]);
	}
}

//树的修改
var treeEdit = new Vue({
	el: "#treeEdit",
	data: function() {
		return {
			showParent: true,
			treeEditVisible: false,
			labelPosition: 'right',
			ruleForm: {
				parentName: '',
				id: '',
				name: '',
				officeTel: ''
			},
			parentName: [],
			rules: {
				name: {
					required: true,
					message: '请输入机构名称',
					trigger: 'blur'
				}
			}
		};
		this.ParentOrgFilter = null;
	},
	methods: {
		submitForm: function(formName) {
			var self = this;
			self.$refs[formName].validate(function(valid) {
				var parentOrgCodeNodeId;
				if(valid) {
					treeEdit.treeEditVisible = false;
					VanyAjax("/base/org/update", {
						parentOrgCode: treeEdit.parentName[0].id,
						orgCode: treeEdit.ruleForm.id,
						orgName: treeEdit.ruleForm.name,
						officeTel: treeEdit.ruleForm.officeTel
					}).done(function(data) {
						var newNode = {
							id: treeEdit.ruleForm.id,
							name: treeEdit.ruleForm.name,
							officeTel: treeEdit.ruleForm.officeTel
						};
						zTree.getSelectedNodes()[0].name = treeEdit.ruleForm.name; //获取名称
						zTree.getSelectedNodes()[0].officeTel = treeEdit.ruleForm.officeTel; //获取电话号码
						//						zTree.removeNode(zTree.getSelectedNodes()[0]);
						//						zTree.addNodes(zTree.getNodeByParam("id", treeEdit.parentName[0].id, null), -1, newNode, false);
						VanyBaseTree("treeDemo", baseUrl + "/base/org/queryOrgTree?token=" + sessionStorage.token, NodeSettingManagement);
						VanyAjax.prototype.hideLoading();
						this.resetForm(true);
					}, false, this);
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		openParentOrg: function() {
			var self = this;
			if(!this.ParentOrgFilter) {
				this.ParentOrgFilter = VanyFilter({
					mountEl: "#content",
					title: "更换父机构",
					tabs: [{
						"name": "父机构选择",
						"id": "bumen",
						"url": baseUrl + "/base/org/queryOrgTreeWithOutSelf?orgCode=" + zTree.getSelectedNodes()[0].id,
						"writeBackIds": this.ruleForm.parentName,
						"singleSelet": true,
						"defaultProps": {
							children: 'children',
							label: 'name',
							id: "id"
						},
						"icon": '/templates/img/zuzhi.png'
					}],
					ok: function() {
						self.parentName = this.tabs[0].allCheckeds;
						if(self.parentName.length == 0) {
							$(".showFirst").hide();
							$(".showSed").show();
						} else {
							$(".showFirst").show();
							$(".showSed").hide();
						}
						self.ruleForm.parentName = this.tabs[0].allNodesId.join(",");
						this.hide();
					}
				});
			} else {
				this.ParentOrgFilter.show();
			}
		},
		resetForm: function(formName) {
			this.parentName = [];
			this.ruleForm.parentName = '';
			this.ruleForm.id = '';
			this.ruleForm.name = '';
			this.ruleForm.officeTel = '';
		} //重置
	}
});

//导入组织
var ImportOrg = new Vue({
	el: "#ImportOrg",
	data: function() {
		return {
			OrgImportVisible: false,
			labelPosition: 'right',
			filename: false,
			token: {
				token: sessionStorage.token
			},
			ruleForm: {
				batch: '',
				state: 1
			}
		};
	},
	methods: {
		handleChange: function(file, fileList) {
			if(fileList.length === 2) {
				fileList.splice(0, 1);
			}
			var isXLS = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
			var isLt2M = file.size / 1024 / 1024 < 2;
			if(!isXLS) {
				this.$message.error('仅支持Excel格式！');
				return;
			}
			if(!isLt2M) {
				this.$message.error('上传文件大小不能超过 2MB!');
				return;
			}
			this.filename = file.name;
		},
		submitForm: function(formName) {
			$(".errorMessage").remove();
			this.$refs.upload.submit();
		},
		handleAvatarSuccess: function(res, file, fileList) {
			var self = this;
			if(res.rspMsg == null) {
				var message = '';
				for(var i = 0; i < res.validateErrMsg.length; i++) {
					var erValidateErrMsg = '',
						errMssage = '';
					erValidateErrMsg = "<ul>" + res.validateErrMsg[i].field + "：</ul>";
					var errMssages = '';
					for(var j = 0; j < res.validateErrMsg[i].message.length; j++) {
						errMssage = "<li>" + res.validateErrMsg[i].message[j] + "</li>";
						errMssages += errMssage
					}
					message += erValidateErrMsg + errMssages;
				}
				$(".el-dialog__body").append('<div class="errorMessage">' + message + '</div>');
			} else {
				this.$message.success(res.rspMsg);
				new VanyBaseTree("treeDemo", baseUrl + "/base/org/queryOrgTree?token=" + sessionStorage.token, NodeSettingManagement);
				ImportOrg.OrgImportVisible = false;
			}
			ImportOrg.$nextTick(function() {
				self.filename = false;
			});
		}
	}
});

////////////--------------表格-数据--------------------////////////
var table_ = new Vue({
	el: '#table',
	data: function() {
		return {
			tableData: [],
			total: 0,
			page: 1, // 默认显示第一页
			orgCode: "",
			pageSize: 10,
			pageIndex: 1,
			status: "",
			hasResetPagination: false,
			nodataFlag: false,
			listLoading: false, // 加载表格数据tableData
			editFormVisible: false, // 编辑界面是否显示
			editLoading: false,
			editFormRules: {
				name: [{
					required: true,
					message: '请输入姓名',
					trigger: 'blur'
				}]
			},
			// 编辑界面数据
			editForm: {
				id: 0,
				dingDanHao: '',
				jiaoYiJinE: '',
				jiaoYiShiJian: '',
				zhiFuFanShi: 0
			},
			// 列表选中列
			sels: [],
			tableHeight: "",
			searchValue: "",
			// 禁用、启用、全部
			stateCounts: [0, 0, 0],
			//curFilter: "全部 (0)",
			curSelectedIndex: 0,
			// 给每一个行数据添加index_索引属性
			_index: 0,
			curTr: {}
		}
	},
	computed: {
		filtersStatusCount: function() {
			return [{
				text: "全部 (" + this.stateCounts[2] + ")",
				value: ""
			}, {
				text: "启用 (" + this.stateCounts[1] + ")",
				value: "1"
			}, {
				text: "禁用 (" + this.stateCounts[0] + ")",
				value: "0"
			}]
		},
		curFilter: function() {
			if(this.status === "1") {
				return "启用(" + this.stateCounts[1] + ")";
			} else if(this.status === "0") {
				return "禁用(" + this.stateCounts[0] + ")";
			} else {
				return "全部(" + this.stateCounts[2] + ")";
			}
		},
		pages: function() {
			return Math.ceil(this.total / this.pageSize);
		}
	},
	mounted: function(value, oldvalue) {
		var self = this;
		this.$el.style.left = "210px";
		this.tableHeight = window.innerHeight - 320;
		var isScrollToBottom_ = function() {
			if(self.nodataFlag || self.hasResetPagination) {
				return false;
			}
			//isScrollToBottom(this, self.getData);
		};
		this.$nextTick(function() {
			// 生成数据后，根据窗口默认table宽度展示
			// console.log("可视区域宽度111" + $("body").width());
			$(this.$el).stop(true, false).animate({
				width: $(".vany_authority").width() - 234
			});
			var tablebody_ = this.$children[1].$el;
			tablebody_ = tablebody_.getElementsByClassName("el-table__body-wrapper")[0];
			tablebody_.onscroll = function(e) {
				throttle(isScrollToBottom_, e);
			}
		});
	},
	methods: {
		// 获取表格数据
		getData: function() {
			if(this.pages!=0&&this.pageIndex>this.pages)
			{
				return;
			}
			console.log(this.pageIndex);
			VanyAjax("/base/org/queryOrgUserList", {
				orgCode: this.orgCode,
				pageSize: this.pageSize,
				pageIndex: this.pageIndex,
				searchValue: this.searchValue,
				status: this.status
			}, "GET", ".el-table").done(function(data) {
				// 全部、禁用、启用计数
				this.stateCounts[0] = data.forBidden;
				this.stateCounts[1] = data.NotForBidden;
				//this.stateCounts[2] = data.total;
				this.stateCounts[2] = data.forBidden + data.NotForBidden;
				// 解决方法重新整体赋值
				this.stateCounts = [].concat(this.stateCounts);
				//this.curFilter = "全部(" + this.stateCounts[2] + ")";
				this.total = data.total;

				for(var i = 0; i < data.rows.length; i++) {
					if(data.rows[i].photoUrl == null) {
						data.rows[i].photoUrl = "/templates/img/default.jpg";
					}
				}
				if(data.total === 0) {
					this.nodataFlag = true;
					this.tableData = [];
					return;
				}
				if(this.pageIndex * this.pageSize >= data.total) {
					this.nodataFlag = true;
				}
				var rows = data.rows;
				this.tableData = [];
				for(var i = 0; i < rows.length; i++) {
					/* 坑，索引赋值无法触发更新 */
					rows[i]._index = this._index;
					this.tableData.push(rows[i]);
					this._index++;
				}
				//this.pageIndex++;
				VanyAjax.prototype.hideLoading();
			}, false, this);
		},
		updateIndex: function() {
			this._index = this.tableData.length;
			for(var i = 0; i < this._index; i++) {
				this.tableData[i]._index = i;
			}
		},
		getIndexById: function(id) {
			for(var i = 0; i < this.tableData.length; i++) {
				if(id === this.tableData[i].userId) {
					return i;
				}
			}
			return false;
		},
		filterStatus: function(command) {
			if(command == this.status) {
				return false;
			}
			this.status = command;
			this.searchTable();
		},
		resetPaginationParams: function() {
			this.tableData = [];
			this.tableData_ = [];
			this.pageIndex = 1;
			this.nodataFlag = false;
			this._index = 0;
		},
		// 表格操作区域下拉选择
		tableSelect: function(command) {
			$("#handleCommand").html(command);
		},
		// 表格操作区域新增人员
		AddTable: function() {
			tanchuDialog(); //弹出框位置
			newPerson.show();
			newPerson.isAdd = true;
			newPerson.form.orgList = table_.orgCode;
			var seletedOrgNode = zTree.getSelectedNodes()[0];
			table_.orgCode = seletedOrgNode.id;
			table_.orgName = seletedOrgNode.name;
			newPerson.orgList.push({
				name: table_.orgName,
				id: table_.orgCode
			});
		},
		// 表格操作区域批量导入
		BatchImport: function() {
			tanchuDialog(); //弹出框位置
			BatchImport.batchImportVisible = true;
		},
		gender: function(row, column) {
			return row.Gender == 1 ? '男' : '女';
		},
		// 選中复选框
		selsChange: function(sels) {
			this.sels = sels;
			this.sels.length !== 0 ? multiSelectPerson.show() : multiSelectPerson.hide()
		},
		 handleCurrentChange: function (val) {
	        	this.pageIndex = val;
	            this.getData();
        },
        handleSizeChange: function(val){
	        	this.pageSize = val;
	            this.getData();
        }
		,
		restoreTableData: function(val) {
			if(val.length === 0) {
				// 还原
				this.searchTable();
			}
		},
		/**
		 * 按搜素关键字过滤表格数据
		 */
		searchTable: function(val) {
				this.getData();
		},
		/**
		 * 表格数据过滤器
		 * 过滤对象: Obj item
		 * return Bool
		 */
		createFilter: function(item, state) {
			for(var key in item) {
				if(item[key].toString().indexOf(this.keyWord) > -1) {
					return true
				}
			}
			return false;
		},
		/**
		 * 点击行时显示个人资料卡片
		 */
		showPersonCard: function(row, event, column) {
			// 如果已经出现批量选择的框，那么点击行的时候就不要展示人员信息了
			if(column.type === "selection" || this.sels.length > 0) {
				return;
			}
			this.curSelectedIndex = this.getIndexById(row.userId);
			this.curTr = row;
			// 坑！后端有些字段没值是不返回该字段的，所以先要重置所有再赋值
			// 不从缓存里拉人员信息了
			/*
			 * for(var key in personCard.personinfo) {
			 * personCard.personinfo[key] = ""; } for(var key in row) {
			 * personCard.personinfo[key] = row[key]; }
			 */
			personCard.getData(row.userId);
		},
		filterTag: function(value, row) {
			return row.State == value;
		},
		// 人员批量导出
		userExport: function() {
			var self = this;
			if(self.orgCode.length !== 0) {
				self.$confirm('是否导出当前所选部门下的所有人员列表?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: "notLoadingThis"
				}).then(function() {
					if(table_.tableData.length === 0) {
						self.$alert('没有数据', '提示', {
							confirmButtonText: '确定'
						});
					} else {
						document.location.href = "/base/user/export?token=" + sessionStorage.token + "&type=ORG&orgCode=" + zTree.getSelectedNodes()[0].id;
					}
				});
			}
		},
	},
	updated: function() {
		Jurisdiction();
	}
});

// 个人资料卡片
var personCard = new Vue({
	el: "#personCard",
	data: {
		personCardVisible: false,
		isIE: !!window.VBArray,
		personinfo: {
			email: "",
			jobPosition: "",
			userName: "",
			status: "",
			statusStr: "",
			mobile: "",
			// 废弃
			photoUrl: "",
			photo: "",
			userAccount: "",
			gender: "",
			genderStr: "",
			wechat: "",
			tel: "",
			department: "",
			orgCodes: "",
			orgList: "",
			tagList: "",
			teamList: "",
			roleList: ""
		},
		keynames: [{
			"name": "账号",
			"value": "userAccount"
		}, {
			"name": "手机",
			"value": "mobile"
		}, {
			"name": "公司电话",
			"value": "tel"
		}, {
			"name": "SesaID",
			"value": "wechat"
		}, {
			"name": "邮箱",
			"value": "email"
		}, {
			"name": "证件号码",
			"value": "identificationNo"
		}, {
			"name": "部门",
			"value": "orgList"
		}, {
			"name": "角色",
			"value": "roleList"
		}]
	},
	computed: {
		/*_index: function(){
			return table_.curSelectedIndex;
		},*/
		StateButtonText: function() {
			return this.personinfo.status === "1" ? "禁用" : "启用"
		},
		statusStr: function() {
			return this.personinfo.status === "1" ? "启用" : "禁用"
		},
		genderStr: function() {
			if(this.personinfo.gender === "1") {
				return "男";
			} else if(this.personinfo.gender === "0") {
				return "女";
			} else {
				return "其他";
			}
		},
		items: function() {
			var self = this;
			return this.keynames.map(function(keyname) {
				var value = self.personinfo[keyname.value];
				if(Object.prototype.toString.call(value) === "[object Array]") {
					var key_ = ["orgName", "tagName", "teamName", "roleName"];
					var icon_ = ["icon-zuzhi", "icon-fenlei", "icon-qunzu", "icon-jiaose"];
					var class_ = ["zuzhi-tag", "fenlei-tag", "qunzu-tag", "jiaose-tag"]
					var index_ = 0;
					var names_ = value.map(function(team) {
						for(var i = 0; i < key_.length; i++) {
							if(team[key_[i]]) {
								index_ = i;
								return team[key_[i]];
							}
						}
					});
					return {
						"name": keyname.name,
						"value": names_,
						"iscategory": true,
						"icon": icon_[index_],
						"tagClass": class_[index_]
					}
				} else {
					return {
						"name": keyname.name,
						// 强制进行类型转换，转到String
						"value": value || "",
						"iscategory": false
					}
				}
			});
		}
	},
	updated: function() {
		// 人员信息卡片
		var dialogBody = this.$el.getElementsByClassName("el-dialog__body")[0];
		// 47是header高度，62是footer高度，
		dialogBody.style.maxHeight = window.innerHeight - 47 - 62 + "px";
		dialogBody.style.overflowY = "auto";
		Jurisdiction();
	},
	methods: {
		/**
		 * 重置密码
		 * resetPassword.userId 传递用户账号
		 * resetPasswordVisible = true显示重置密码框
		 */
		resetPassword: function() {
			resetPassword.show()
			resetPassword.userId = this.personinfo.userId;
		},
		disabledOrEnablePerson: function() {
			var self = this;
			self.$confirm('确定' + self.StateButtonText + '此用户？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				VanyAjax("/base/user/resetUserStatus", {
					userId: self.personinfo.userId,
					status: self.personinfo.status === "0" ? "1" : "0"
				}).done(function(data) {
					if(self.personinfo.status === "0") {
						self.personinfo.status = "1";
						self.personinfo.statusStr = "启用";

						table_.curTr.status = "1";
						table_.curTr.statusStr = "启用";
					} else {
						self.personinfo.status = "0";
						self.personinfo.statusStr = "禁用";

						table_.curTr.status = "0";
						table_.curTr.statusStr = "禁用";
					}
					VanyAjax.prototype.hideLoading();
				});
			})
			/*.catch(function() {
				self.$message({
					type: 'info',
					message: '取消修改'
				});
			});*/
		},
		movePerson: function() {
			if(!this.orgFilter) {
				// self指向Vue实例
				var self = this;
				this.orgFilter = VanyFilter({
					mountEl: "#content",
					title: "请选择要移动到的部门",
					tabs: [{
						"name": "部门",
						"id": "bumen",
						"url": baseUrl + "/base/org/queryOrgTree?token=" + token,
						"icon": '/templates/img/zuzhi.png'
					}],
					ok: function() {
						// self_指向筛选器
						var self_ = this;
						self_.$confirm('是否移动用户到' + self_.tabs[0].allCheckeds[0].name + '?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(function() {
							VanyAjax("/base/user/moveUsers", {
								userIdList: self.personinfo.userId,
								// 变动为取table当前所选
								/*orgUserIdList: self.personinfo.orgList.map(function(item) {
									return item.orgUserId;
								}).join(","),*/
								orgUserIdList: table_.curTr.orgUserId,
								orgCodeList: self_.tabs[0].allNodesId.join(",")
							}).done(function(data) {
								this.destroy();
								self.orgFilter = null;
								table_.tableData.splice(table_.curSelectedIndex, 1);
								personCard.hide();
							}, true, self_);
						}).catch(function() {
							// pass
						});
						return false;
					}
				});
			} else {
				this.orgFilter.show();
			}
		},
		nofindImg: function(e) {
			e.srcElement.src = "/templates/img/default.jpg";
		},
		deletePerson: function() {
			var self = this;
			this.$confirm('确认删除该用户？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				VanyAjax("/base/user/deleteUsers", {
					userIdList: self.personinfo.userId
				}).done(function(data) {
					table_.tableData.splice(table_.curSelectedIndex, 1);
					personCard.hide();
				}, true, self);
			}).catch(function() {})
		},
		EditPerson: function() {
			newPerson.show();
			newPerson.isAdd = false;
			/**
			 * 注意不能直接整个对象赋值（引用赋值）更新
			 * newPerson.form = this.personinfo;
			 * 否则导致修改信息的时候，个人资料对话框的信息也会跟着改动
			 */
			for(var key in this.personinfo) {
				var notFormKeys = ["photoUrl", "notShowTeams", "notShowRoles", "notShowTags", "notShowOrgs"];
				if(notFormKeys.indexOf(key) > -1) {
					newPerson[key] = this.personinfo[key];
				} else {
					newPerson.form[key] = this.personinfo[key];
				}
			}
			// 手动转换以下字段格式
			// *List由数组变为逗号隔开的字符串
			var key_ = ["org", "tag", "team", "role"];
			for(var i = 0; i < key_.length; i++) {
				var arrKey = key_[i] + "List",
					idKey = key_[i] + "Code",
					nameKey = key_[i] + "Name";
				newPerson.form[arrKey] = this.personinfo[arrKey].map(function(item) {
					newPerson[arrKey].push({
						id: item[idKey],
						name: item[nameKey]
					});
					return item[idKey];
				}).join(",");
			}
		},
		canleSelect: function() {
			table_.$refs["table"].setCurrentRow();
			try {
				this.orgFilter.destroy();
				this.orgFilter = null;
			} catch(e) {

			}
		},
		show: function() {
			this.personCardVisible = true;
			if(this.isIE) {
				this.$el.getElementsByClassName("el-dialog__wrapper")[0].style.left = (window.innerWidth) - 400 + "px";
			}
			return this;
		},
		hide: function() {
			this.personCardVisible = false;
			return this;
		},
		getData: function(userId) {
			VanyAjax("/base/org/queryUserInfo", {
				userId: userId
			}, "GET", "#personCard .el-dialog").done(function(data) {
				for(var key in data) {
					var self = this;
					if(key === "photoUrl") {
						if(data[key] == '' || data[key] == null) {
							self.personinfo[key] = "/templates/img/default.jpg";
						} else {
							self.personinfo[key] = data[key] + "?" + +new Date();
						}
					} else {
						self.personinfo[key] = data[key];
					}
				}
				this.show();
			}, false, this);
		}
		//	},
		//	updated: function() {
		//		Jurisdiction();
	}
});

// 人员多选操作
var multiSelectPerson = new Vue({
	el: "#multiSelectPerson",
	data: {
		multiSelectPersonVisible: false,
		isIE: !!window.VBArray
	},
	computed: {
		seletedPersons: function() {
			return table_.sels;
		},
		title: function() {
			return "批量选择(" + table_.sels.length + ")";
		}
	},
	updated: function() {
		// 全选人员滚动条
		var dialogBody = this.$el.getElementsByClassName("el-dialog__body")[0];
		// 47是header高度，62是footer高度，
		dialogBody.style.maxHeight = window.innerHeight - 47 - 62 + "px";
		dialogBody.style.overflowY = "auto";
		Jurisdiction();
	},
	methods: {
		show: function() {
			this.multiSelectPersonVisible = true;
			if(this.isIE) {
				this.$el.getElementsByClassName("el-dialog__wrapper")[0].style.left = (window.innerWidth) - 400 + "px";
			}
		},
		hide: function() {
			this.multiSelectPersonVisible = false;
		},
		/**
		 * 移动所选人员
		 */
		moveSeletedPerson: function() {
			if(!this.orgFilter) {
				// self指向Vue实例
				var self = this;
				this.orgFilter = VanyFilter({
					mountEl: "#content",
					title: "请选择要移动到的部门",
					tabs: [{
						"name": "部门",
						"id": "bumen",
						"url": baseUrl + "/base/org/queryOrgTree?token=" + token,
						"icon": '/templates/img/zuzhi.png'
					}],
					ok: function() {
						// self_指向筛选器
						var self_ = this;
						self_.$confirm('是否进行移动操作？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(function() {
							VanyAjax("/base/user/moveUsers", {
								userIdList: self.seletedPersons.map(function(item) {
									return item.userId;
								}).join(","),
								orgUserIdList: self.seletedPersons.map(function(item) {
									return item.orgUserId;
								}).join(","),
								orgCodeList: self_.tabs[0].allNodesId.join(",")
							}).done(function(data) {
								this.destroy();
								self.orgFilter = null;
								self.remove();
							}, true, self_);
						}).catch(function() {
							// pass
						});
						return false;
					}
				});
			} else {
				this.orgFilter.show();
			}
		},
		/**
		 * 删除所选人员
		 */
		deleteSeletedPerson: function() {
			var userIdList = this.seletedPersons.map(function(item) {
				return item.userId;
			}).join(",");
			var self = this;
			this.$confirm('确认删除该所选用户？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				VanyAjax("/base/user/deleteUsers", {
					userIdList: userIdList
				}).done(function(data) {
					this.remove();
					/*var sels = [].concat(table_.sels);
					sels = this.quickSort(sels, "_index");
					for(var i = 0; i < sels.length; i++) {
						table_.tableData.splice(sels[i]._index, 1);
						for(var j = i + 1; j < sels.length; j++) {
							sels[j]._index--;
						}
					}
					table_.sels = [];*/
					table_.updateIndex();
					multiSelectPerson.hide();
				}, true, self);
			}).catch(function() {})
		},
		remove: function() {
			var sels = [].concat(table_.sels);
			sels = this.quickSort(sels, "_index");
			for(var i = 0; i < sels.length; i++) {
				table_.tableData.splice(sels[i]._index, 1);
				for(var j = i + 1; j < sels.length; j++) {
					sels[j]._index--;
				}
			}
			table_.sels = [];
		},
		/**
		 * 从所选择人员中移除
		 * 移除类别: Number rowindex
		 * rowindex如果不传则表示移除所有，默认只移除指定项
		 */
		removeFromSeleted: function(rowindex) {
			// 使用splice而不是table_.$refs["table"].clearSelection(table_.sels[rowindex])
			// 是因为会导致循环的数据引用，清空一个会清空所有
			rowindex !== undefined ? table_.sels.splice(rowindex, 1) : table_.$refs["table"].clearSelection()
			// sels为空时应该关闭弹框
			if(table_.sels.length === 0) {
				multiSelectPerson.hide();
			}
		},
		quickSort: function(arr, _key) {
			if(arr.length <= 1) {
				return arr;
			}
			var pivotIndex = Math.floor(arr.length / 2),
				pivot = arr.splice(pivotIndex, 1)[0],
				left = [],
				right = [];
			if(_key) {
				for(var i = 0; i < arr.length; i++) {
					if(arr[i][_key] < pivot[_key]) {
						left.push(arr[i]);
					} else {
						right.push(arr[i]);
					}
				}
				return this.quickSort(left, _key).concat([pivot], this.quickSort(right, _key));
			} else {
				for(var i = 0; i < arr.length; i++) {
					if(arr[i] < pivot) {
						left.push(arr[i]);
					} else {
						right.push(arr[i]);
					}
				}
				return this.quickSort(left, _key).concat([pivot], this.quickSort(right, _key));
			}
		}
	}
});

// 重置密码
var resetPassword = new Vue({
	el: "#resetPassword",
	data: function() {
		var validateAdminpassword = function(rule, value, callback) {
			if(value === '') {
				callback(new Error('请输入管理员密码'));
			} else {
				callback();
			}
		};
		return {
			resetPasswordVisible: false,
			restSucceed: false,
			userPassword: "",
			userId: "",
			formLabelWidth: "120px",
			form: {
				adminpassword: ""
			},
			rules: {
				adminpassword: [{
					validator: validateAdminpassword,
					trigger: 'blur'
				}]
			}
		}
	},
	methods: {
		submitResetPassword: function(formName, e) {
			console.log(e)
			var self = this;
			this.$refs[formName].validate(function(valid) {
				if(valid) {
					VanyAjax("/base/user/resetUserPassword", {
						userId: self.userId,
						password: self.form.adminpassword
					}).done(function(data) {
						this.userPassword = data.userPassword;
						this.restSucceed = true;
					}, true, self);
				} else {
					e.stopPropagation();
					return false;
				}
			});
			e.stopPropagation();
			return false;
		},
		resetData: function() {
			//this.$refs["form"].resetFields();
			this.form.adminpassword = "";
			this.restSucceed = false;
		},
		show: function() {
			try{
				this.$refs["form"].resetFields();
			}catch(e){}
			this.resetPasswordVisible = true;
			return this;
		},
		hide: function() {
			this.resetPasswordVisible = false;
			return this;
		}
		//	},
		//	updated: function() {
		//		Jurisdiction();
	}
});

// 新增人员
var newPerson = new Vue({
	el: "#newPerson",
	data: function() {
		this.orgFilter = null;
		this.teamFilter = null;
		this.tagFilter = null;
		this.roleFilter = null;
		var self = this;
		return {
			newPersonVisible: false,
			labelPosition: "left",
			isAdd: true,
			// 用于展示，图片的保存路径
			photoUrl: "/templates/img/default.jpg",
			form: {
				userName: "",
				userAccount: "",
				userId: "",
				gender: "1",
				status: "1",
				mobile: "",
				tel: "",
				jobPosition:"",
				identificationTypeCode: "01",
				email: "",
				identificationNo: "",
				// 用于上传图片
				photo: "",
				wechat: "",
				department: "",
				orgCodes: "",
				orgList: "",
				teamList: "",
				tagList: "",
				roleList: ""
			},
			orgList: [],
			teamList: [],
			tagList: [],
			roleList: [],
			identificationTypeCode: [],
			jobPosition: [],
			rules: {
				userName: [{
					required: true,
					message: "名称不能为空",
					trigger: 'blur'
				}],
				userAccount: [{
					required: true,
					message: "账号不能为空",
					trigger: 'blur'
				}],
				orgList: [{
					required: true,
					message: "所在部门不能为空",
					trigger: 'blur',
					validator: function(rule, value, callback) {
						if(self.isAdd) {
							if(value === "") {
								callback(new Error("所在部门不能为空"));
							} else {
								callback();
							}
						} else {
							callback();
						}
					}
				}],
				tel: [{
					trigger: 'blur',
					validator: function(rule, value, callback) {
						if(value === "" || value === null) {
							callback();
						} else {
							if(!/^[0-9]*$/.test(value)) {
								callback(new Error("电话号码只能为纯数字"));
							} else {
								callback();
							}
						}
					}
				}],
				mobile: [{
					required: false,
					trigger: 'blur',
					validator: function(rule, value, callback) {
						if(value === "" || value === null) {
							callback();
						} else {
							if(!(/1(?:[38]\d|4[4579]|5[0-35-9]|7[35678])\d{8}/.test(value))) {
								callback(new Error("请输入正确的手机号"));
							} else {
								callback();
							}
						}
					}
				}],
				email: [{
					type: 'email',
					message: '请输入正确的邮箱地址',
					trigger: 'blur'
				}]
			}
		}
	},
	computed: {
		title: function() {
			return this.isAdd ? "新增人员" : "编辑人员"
		}
	},
	created: function() {
		VanyAjax("/base/dictionary/identification", {}).done(function(data) {
			for(var i = 0; i < data.length; i++) {
				this.identificationTypeCode.push({
					value: data[i].identificationTypeCode,
					label: data[i].identificationTypeName
				});
			}
		}, false, this);
		
		VanyAjax("/base/dictionary/industry", {}).done(function(data) {
			for(var i = 0; i < data.length; i++) {
				this.jobPosition.push({
					value: data[i].industryCode,
					label: data[i].industryName
				});
			}
		}, false, this);
	},
	methods: {
		beforeAvatarUpload: function(file) {
			var isJPG = file.type === 'image/jpeg';
			var isLt2M = file.size / 1024 / 1024 < 2;

			if(!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!');
			}
			if(!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isJPG && isLt2M;
		},
		save: function(nextdo) {
			var self = this;
			this.$refs["newPersonForm"].validate(function(valid) {
				if(!valid) {
					return false;
				} else {
					var url_ = "/base/user/add";
					if(!self.isAdd) {
						url_ = "/base/user/update";
						// 处理不显示的部门、群组、标签、角色
						//var notShow = ["Org", "Team", "Tag", "Role"];
//						for(var i = 0; i < notShow.length; i++) {
//							// 形如notShowOrgs
//							var notShowThis = "notShow" + notShow[i] + "s";
//							var notShowList = self[notShowThis].map(function(item) {
//								// 形如orgCode
//								var idKey = notShow[i].toLowerCase() + "Code";
//								return item[idKey];
//							}).join(",");
//							if(notShowList != "") {
//								// 形如orgList
//								var idKey = notShow[i].toLowerCase() + "List";
//								if(self.form[idKey]) {
//									self.form[idKey] = self.form[idKey] + "," + notShowList;
//								} else {
//									self.form[idKey] = notShowList;
//								}
//							}
//						}
						/*// 处理不显示的部门
						var notShowOrgList = self.notShowOrgs.map(function(item) {
							return item.orgCode;
						}).join(",");
						if(notShowOrgList !== "") {
							if(self.form.orgList) {
								self.form.orgList = self.form.orgList + "," + notShowOrgList;
							} else {
								self.form.orgList = notShowOrgList
							}
						}

						// 处理不显示的群组
						var notShowTeamList = self.notShowTeams.map(function(item) {
							return item.teamCode;
						}).join(",");
						if(notShowTeamList !== "") {
							if(self.form.teamList) {
								self.form.teamList = self.form.teamList + "," + notShowTeamList;
							} else {
								self.form.teamList = notShowTeamList
							}
						}

						// 处理不显示的分类
						var notShowTagList = self.notShowTags.map(function(item) {
							return item.tagCode;
						}).join(",");
						if(notShowTagList !== "") {
							if(self.form.tagList) {
								self.form.tagList = self.form.tagList + "," + notShowTagList;
							} else {
								self.form.tagList = notShowTagList
							}
						}

						// 处理不显示的角色
						var notShowRoleList = self.notShowRoles.map(function(item) {
							return item.roleCode;
						}).join(",");
						if(notShowRoleList !== "") {
							if(self.form.roleList) {
								self.form.roleList = self.form.roleList + "," + notShowRoleList;
							} else {
								self.form.roleList = notShowRoleList
							}
						}*/
					}
					VanyAjax(url_, self.form).done(function(data) {
						// 继续添加
						if(nextdo === "add") {
							self.resetForm(false);
						} else {
							if(!self.isAdd) {
								personCard.getData(self.form.userId);
								for(var key in self.form) {
									table_.curTr[key] = self.form[key];
								}
								table_.curTr["photoUrl"] = table_.curTr["photoUrl"] + "?" + +new Date();
							}
							table_.getData();
							this.close();
						}
					}, true, self);
				}
			});
		},
		resetForm: function(isResetFilter) {
			this.$refs["newPersonForm"].resetFields();
			this.form.userName = "";
			this.form.userId = "";
			this.form.userAccount = "";
			this.form.gender = "1";
			this.form.status = "1";
			this.form.mobile = "";
			this.form.tel = "";
			this.form.jobPosition="";
			this.form.email = "";
			this.form.identificationNo = "";
			this.form.identificationTypeCode = "01";
			this.photoUrl = "/templates/img/default.jpg";
			this.form.photo = "";
			this.form.wechat = "";
			// 添加人员不要
			this.form.department = "";
			this.form.teamList = "";
			this.form.tagList = "";
			this.form.orgList = "";
			this.form.roleList = "";
			this.teamList = [];
			this.tagList = [];
			this.orgList = [];
			this.roleList = [];
			// 暂时不要
			// this.form.Role = "";
			if(isResetFilter) {
				try {
					this.orgFilter.destroy();
					this.tagFilter.destroy();
					this.teamFilter.destroy();
					this.roleFilter.destroy();
				} catch(e) {

				} finally {
					this.orgFilter = null;
					this.tagFilter = null;
					this.teamFilter = null;
					this.roleFilter = null;
				}
			}
		},
		/* 重置表单值 */
		close: function() {
			this.resetForm(true);
			this.hide();
		},
		handleChange: function(file, fileList) {
			avaterCropper.dialogVisible = true;
			avaterCropper.imgSrc = file.url;
			setTimeout(function() {
				avaterCropper.initCropper("avater_be_cropper");
			}, 500);
		},
		show: function() {
			this.newPersonVisible = true;
			return this;
		},
		hide: function() {
			this.newPersonVisible = false;
			return this;
		},
		// 组织筛选器
		oepnOrgFilter: function() {
			var self = this;
			if(!this.orgFilter) {
				this.orgFilter = VanyFilter({
					mountEl: "#content",
					title: "所在部门",
					tabs: [{
						"name": "部门",
						"id": "bumen",
						"url": baseUrl + "/base/org/queryOrgTree?token=" + token,
						"writeBackIds": this.form.orgList,
						"icon": '/templates/img/zuzhi.png'
					}],
					ok: function() {
						self.orgList = this.tabs[0].allCheckeds;
						self.form.orgList = this.tabs[0].allNodesId.join(",");
						this.hide();
					}
				});
			} else {
				this.orgFilter.writeBack("bumen", this.form.orgList);
				this.orgFilter.show();
			}
		},
		// 群组筛选器
		openTeamFilter: function() {
			var self = this;
			if(!this.teamFilter) {
				this.teamFilter = VanyFilter({
					mountEl: "#content",
					title: "所属群组",
					tabs: [{
						"name": "群组",
						"id": "qunzu",
						"url": baseUrl + "/base/team/load?token=" + token,
						"writeBackIds": this.form.teamList,
						"icon": '/templates/img/qunzu.png',
						"defaultProps": {
							children: 'children',
							label: 'teamName',
							id: "teamCode"
						},
					}],
					ok: function() {
						self.teamList = this.tabs[0].allCheckeds;
						self.form.teamList = this.tabs[0].allNodesId.join(",");
						this.hide();
					}
				});
			} else {
				this.teamFilter.writeBack("bumen", this.form.teamList);
				this.teamFilter.show();
			}
		},
		// 分类筛选器
		openTagFilter: function() {
			var self = this;
			if(!this.tagFilter) {
				this.tagFilter = VanyFilter({
					mountEl: "#content",
					title: "所属分类",
					tabs: [{
						"name": "公共分类",
						"id": "gonggongfenlei",
						"url": baseUrl + "/base/tag/loadTag?tagType=1&token=" + token,
						"icon": '/templates/img/fenlei.png',
						"writeBackIds": this.form.tagList,
						"defaultProps": {
							children: 'children',
							label: 'tagName',
							id: "tagCode"
						},
					}, {
						"name": "我的分类",
						"id": "wodefenlei",
						"url": baseUrl + "/base/tag/loadTag?tagType=0&token=" + token,
						"icon": '/templates/img/fenlei.png',
						"writeBackIds": this.form.tagList,
						"defaultProps": {
							children: 'children',
							label: 'tagName',
							id: "tagCode"
						},
					}],
					ok: function() {
						self.tagList = this.tabs[0].allCheckeds;
						self.tagList = self.tagList.concat(this.tabs[1].allCheckeds)
						self.form.tagList = this.tabs[0].allNodesId.join(",") + ",";
						self.form.tagList += this.tabs[1].allNodesId.join(",");
						this.hide();
					}
				});
			} else {
				this.tagFilter.writeBack("gonggongfenlei", this.form.tagList);
				this.tagFilter.writeBack("wodefenlei", this.form.tagList);
				this.tagFilter.show();
			}
		},
		// 角色筛选器
		openRoleFilter: function() {
			var self = this;
			if(!this.roleFilter) {
				this.roleFilter = VanyFilter({
					mountEl: "#content",
					title: "所属角色",
					tabs: [{
						"name": "角色",
						"id": "jiaose",
						"url": baseUrl + "/sys/role/loadRoleInfo?token=" + token,
						"icon": '/templates/img/juese.png',
						"writeBackIds": this.form.roleList,
						"defaultProps": {
							children: 'children',
							label: 'roleName',
							id: "roleCode"
						},
					}],
					ok: function() {
						self.roleList = this.tabs[0].allCheckeds;
						self.form.roleList = this.tabs[0].allNodesId.join(",");
						this.hide();
					}
				});
			} else {
				this.roleFilter.writeBack("jiaose", this.form.roleList);
				this.roleFilter.show();
			}
		}
		//	},
		//	updated: function() {
		//		Jurisdiction();
	}
});

/* 头像裁剪器 */
var avaterCropper = new Vue({
	el: "#avaterCropper",
	data: function() {
		return {
			dialogVisible: false,
			imgSrc: "",
			cropper: ""
		}
	},
	methods: {
		updateAvater: function(isUpated) {
			if(isUpated) {
				var canvas = this.cropper.getCroppedCanvas({
					width: 320,
					height: 320
				});
				newPerson.form.photo = canvas.toDataURL('image/jpeg');
				newPerson.photoUrl = canvas.toDataURL('image/jpeg');
			}
			this.imgSrc = "";
			this.cropper.destroy();
			this.dialogVisible = false;
		},
		initCropper: function(imgEl) {
			var image_ = document.getElementById(imgEl);
			this.cropper = new Cropper(image_, {
				viewMode: 1,
				aspectRatio: 1 / 1
			});
		}
		//	},
		//	updated: function() {
		//		Jurisdiction();
	}
});

// 批量导入
var BatchImport = new Vue({
	el: "#BatchImport",
	data: function() {
		this.orgFilter = null;
		return {
			batchImportVisible: false,
			labelPosition: 'top',
			filename: false,
			form: {},
			ruleForm: {
				batch: '',
				state: 1,
				orgList: ""
			},
			orgList: []
		}
	},
	methods: {
		show: function() {
			this.batchImportVisible = true;
		},
		hide: function() {
			this.batchImportVisible = false;
		},
		openOrgFilter: function() {
			var self = this;
			if(!this.orgFilter) {
				this.orgFilter = VanyFilter({
					mountEl: "#content",
					title: "所在部门",
					tabs: [{
						"name": "部门",
						"id": "bumen",
						"url": baseUrl + "/base/org/queryOrgTree?token=" + token,
						"singleSelet": true
					}],
					ok: function() {
						self.orgList = this.tabs[0].allCheckeds;
						self.ruleForm.orgList = this.tabs[0].allNodesId.join(",");
						this.hide();
						VanyAjax.prototype.hideLoading();
					}
				});
			} else {
				this.orgFilter.show();
			}
		},
		handleSuccess: function(res, file) {
			if(res.rspCode=='000000')
			{
					this.$message.success(res.rspMsg);
					BatchImport.batchImportVisible = false;
			}else{
				this.$message.error(res.rspMsg);
				BatchImport.batchImportVisible = true;
			}
			var self = this;
			BatchImport.$nextTick(function() {
				self.filename = false;
			});
		},
		handleChange: function(file, fileList) {
			//传参
			var choiceState;
			BatchImport.ruleForm.state === 1 ? choiceState = "COVER" : choiceState = "IGNORE";
			BatchImport.form = {
				token: sessionStorage.token,
				repeatDeal: choiceState,
				orgCode: BatchImport.ruleForm.orgList
			}
			if(fileList.length === 2) {
				fileList.splice(0, 1);
			}
			console.log(fileList);
			var isXLS = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
			var isLt2M = file.size / 1024 / 1024 < 2;
			if(!isXLS) {
				this.$message.error('仅支持Excel格式！');
				return;
			}
			if(!isLt2M) {
				this.$message.error('上传文件大小不能超过 2MB!');
				return;
			}
			this.filename = file.name;
		},
		submitForm: function(formName) {
			if(!this.filename) {
				this.$message.error('请选择文件！');
				return;
			}
			var choiceState;
			BatchImport.ruleForm.state === 1 ? choiceState = "COVER" : choiceState = "IGNORE";
			BatchImport.form = {
				token: sessionStorage.token,
				repeatDeal: choiceState,
				orgCode: BatchImport.ruleForm.orgList
			}
			this.$refs.upload.submit();
			this.$refs.ruleForm.resetFields();
			BatchImport.orgList = [];
			BatchImport.ruleForm.state = 1;
			table_.getData();
		}
		//	},
		//	updated: function() {
		//		Jurisdiction();
	}
});

/**
 * 函数节流器，在时间间隔内不触发函数（优化）
 * 应用场景：需要反复重复执行的事件，如快速重复点击按钮等等
 * method: 函数 function a(){}
 * throttle(a)
 */
function throttle(method, context) {
	clearTimeout(method.tId);
	method.tId = setTimeout(function() {
		method.call(context);
	}, 300);
}

/**
 * 判断一个可滚动元素是否滚动到了底部
 * e: 元素
 * fn: 滚动到底部需要执行的回调
 * isScrollToBottom(div, function(){})
 */
function isScrollToBottom(e, fn) {
	// e.srcElement存在兼容性问题，并非标准特性
	// https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
	// 支持 IE6-8
	var target_ = e.target || e.srcElement,
		// 距离顶部高度
		scrollTop = target_.scrollTop,
		// 滚动区域高度
		scrollHeight = target_.scrollHeight,
		// 文档元素高度
		clientHeight = target_.clientHeight;
	
	//alert(scrollTop+"+"+clientHeight+"="+scrollHeight);
	
	// 文档坐标和视口坐标转换，判断元素滚动到了底部
	if(scrollTop + clientHeight == scrollHeight&&scrollTop!=0) {
		if(fn) {
			//alert(3);
			fn.call();
		}
	}
}

/**
 * 将源对象合并到目标对象中去——内部方法
 * src: 源对象
 * to: 目标对象
 * return 目标对象
 * a = {"a": "a"}
 * b = {"b": "b"}
 * extend_(b, a) → {a: "a", b: "b"}
 */
function extend_(srcObj, toObj) {
	for(var key in srcObj) {
		toObj[key] = toObj[key];
	}
	return toObj;
}

/**
 * 判断是否为字符串
 * o: 对象
 * isString_("string") → true
 * isString_([]) → false
 */
function isString_(o) {
	return Object.prototype.toString.call(o) === "[object String]";
}